from threading import Lock
import datetime
import time
class ReturnBuffer:
    def __init__(self):
        self.buf = []
        self.lock = Lock()

    def clear(self):
        self.lock.acquire()
        self.buf.clear()
        self.lock.release()

    def store_return(self, key, value):
        self.lock.acquire()
        self.buf.append(key + ':' +value)
        self.lock.release()

    def verify_return(self, expect, timeout=2):
        start_time = datetime.datetime.now()
        now_time = datetime.datetime.now()
        while (now_time-start_time).seconds < timeout:
            ret = self._verify_return(expect)
            if ret:
                return
            time.sleep(0.2)
            now_time = datetime.datetime.now()
        assert False, '期望return:%s\n  当前return:%s' % (expect, self.to_string())

    def _verify_return(self, expect):
        self.lock.acquire()
        for return_value in self.buf:
            api = expect.split(':', 1)[0]
            value = expect.split(':', 1)[1]
            if api in return_value:
                rValue = return_value.rsplit(':', 1)[1]
                if value == rValue:
                    self.lock.release()
                    return True
        self.lock.release()
        return False

    def wait_return(self, function_name, timeout=2):
        start_time = datetime.datetime.now()
        now_time = datetime.datetime.now()
        while (now_time - start_time).seconds < timeout:
            ret = self._wait_return(function_name)
            if ret:
                return
            time.sleep(0.2)
            now_time = datetime.datetime.now()


    def _wait_return(self, function_name):
        self.lock.acquire()
        for return_value in self.buf:
            if function_name in return_value:
                self.lock.release()
                return True
        self.lock.release()
        return False

    def to_string(self):
        self.lock.acquire()
        string = ''
        for ret in self.buf:
            string = string + ret + '\n'
        self.lock.release()
        return string



if __name__ == '__main__':
    returnbuff = ReturnBuffer()
    print(returnbuff.to_string())
